package com.base.scanner;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.media3.common.MediaItem;
import androidx.media3.common.PlaybackException;
import androidx.media3.common.Player;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.ui.PlayerView;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;

import com.base.R;

import java.io.File;

public class VideoPlayerActivity extends AppCompatActivity {


    private ExoPlayer player;

    public static void start(Context context, String filePath) {
        Intent intent = new Intent(context, VideoPlayerActivity.class);
        intent.putExtra(FileAdapter.FILE_KEY, filePath);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_player);

        String filePath = getIntent().getStringExtra(FileAdapter.FILE_KEY);

        PlayerView playerView = findViewById(R.id.video_player);
        player = new ExoPlayer.Builder(this).build();

        playerView.setPlayer(player);

        Uri videoUri = FileProvider.getUriForFile(this, "com.recovery.spring01.fileProvider", new File(filePath));
        // Build the media item.
        MediaItem mediaItem = MediaItem.fromUri(videoUri);
        // Set the media item to be played.
        player.setMediaItem(mediaItem);
        // Prepare the player.
        player.prepare();
        // Start the playback.
        player.play();

        player.addListener(new Player.Listener() {

            @Override
            public void onPlayerError(@NonNull PlaybackException error) {
                Player.Listener.super.onPlayerError(error);
                player.seekTo(0);
                player.pause();
                Toast.makeText(VideoPlayerActivity.this, "play err", Toast.LENGTH_SHORT).show();
            }
        });
    }

    boolean isPlaying;

    @Override
    protected void onPause() {
        super.onPause();
        if (player != null) {
            isPlaying = player.isPlaying();
            player.pause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isPlaying) {
            if (player != null) {
                player.play();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (player != null) {
            try {
                player.stop();
                player.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}